package sago

import (
	"fmt"
	"hash/crc32"
	"sync"
	"gopkg.in/mgo.v2"
)

type Mongodb struct {
	SessionList []*mgo.Session
}

var (
	onceMongodb sync.Once
	mongodbSessionList []*mgo.Session
)

func (m *Mongodb) Select(key string) *mgo.Session {
	sessionNum := len(m.SessionList)
	sessionKey := crc32.ChecksumIEEE([]byte(key)) % uint32(sessionNum)
	return m.SessionList[sessionKey]
}

//创建mongodb连接池
func CreateMongodbSessionList() []*mgo.Session {
	addrListStr := GConfig.Mongodb.Addr
	if addrListStr == "" {
		return make([]*mgo.Session, 0)
	}

	if len(mongodbSessionList) > 0 {
		return mongodbSessionList
	} else {
		//获取实例list
		var addrList []string
		decodeErr := Tool.JsonDecode(GConfig.Mongodb.Addr, &addrList)
		if decodeErr != nil {
			panic(decodeErr)
		}
		mongodbSessionList = make([]*mgo.Session, len(addrList))

		onceMongodb.Do(func() {
			for key, addr := range addrList {
				var err error
				url := "mongodb://" + GConfig.Mongodb.Username + ":" + GConfig.Mongodb.Password + "@" + addr + "/" + GConfig.Mongodb.Dbname
				mongodbSessionList[key], err = mgo.Dial(url)
				if err != nil {
					panic(fmt.Sprintln("mongodb连接失败", url, err))
				}
			}
		})
		return mongodbSessionList
	}
}
